import { BrowserWindow, ipcMain, session } from 'electron'

async function handleOpenMainWindow(params: OpenWindowParams, mainWindow: BrowserWindow) {
  const cookies = session.defaultSession.cookies
  const newChildWindow = new BrowserWindow({
    width: 800,
    height: 600,
    maximizable: false
  })
  newChildWindow.setMenu(null)
  newChildWindow.loadURL(params.url)

  const newSession = newChildWindow.webContents.session

  // 每次清掉缓存的cookie
  // newSession.clearStorageData()

  newSession.cookies.on('changed', async () => {
    const userToken = await cookies.get({ url: params.url, name: 'token' })
    if (userToken[0]?.value) {
      // 拿到token之后关闭窗口
      // 并且给渲染进程一个回调
      if (!newChildWindow.isDestroyed()) {
        newChildWindow.close()
        mainWindow.webContents.send('ipcMainSendUserToken', { token: userToken[0]?.value })
      }
    }
  })

  //
}

export function setupModuleWindow(mainWindow: BrowserWindow) {
  ipcMain.on('ipcMainOpenWindow', (_, params) => handleOpenMainWindow(params, mainWindow))
}
